package com.topInterview;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: huangzhigao
 * @Date: 2022/2/13 16:43
 */
public class LeetCode15_ThreeSum {
    //累加和为0
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        for (int i = 0; i < nums.length - 2; i++) {
            if (nums[i] > 0) {
                break;
            }
            if (i == 0 || nums[i] != nums[i - 1]) {
                List<List<Integer>> lists = twoSum(nums, i + 1, 0 - nums[i]);
                for (List<Integer> next : lists) {
                    next.add(nums[i]);
                    ans.add(next);
                }
            }
        }
        return ans;
    }


    public List<List<Integer>> twoSum(int[] nums, int start, int target) {
        int left = start;
        int right = nums.length - 1;
        List<List<Integer>> ans = new ArrayList<>();
        while (left < right) {
            if (nums[left] + nums[right] < target) {
                left++;
            } else if (nums[left] + nums[right] > target) {
                right--;
            } else {
                if (left == start || nums[left] != nums[left - 1]) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[left]);
                    list.add(nums[right]);
                    ans.add(list);
                }
                left++;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        int[] arr = {-1, 0, 1, 2, -1, -4};
        LeetCode15_ThreeSum leetCode15_threeSum = new LeetCode15_ThreeSum();
        leetCode15_threeSum.threeSum(arr);
    }
}
